<!-- 项目成员 -->
<template>
  <div>
    <!-- 成员列表 -->
    <s-table
      :columns="$auth('PROJECT.PROJECT_MEMBER_LIST') ? memberColumns: []"
      bordered
      :data="loadMemberData"
      :row-key="record => record.id"
      ref="memberTableRef"
    >
      <template slot="title">
        <div style="display: flex;justify-content:space-between;">
          <span class="title">{{ $t('all.autotext755') }}</span>
          <div>
            <a-space>
              <a-button @click="getRecord" v-if="$auth('PROJECT.PROJECT_MEMBER_RECORD')">{{ $t('all.autotext518') }}</a-button>
              <a-button
                type="primary"
                icon="plus"
                @click="activeAddMembers()"
                :disabled="projectClosed"
                v-if="$auth('PROJECT.PROJECT_MEMBER_ADD')"
              >
                {{ $t('all.autotext176') }}
              </a-button>
            </a-space>
          </div>
        </div>
      </template>
      <template slot="index" slot-scope="text, record, index">
        <span>{{ index + 1 }}</span>
      </template>
      <template slot="flag" slot-scope="text, record">
        <div class="group-status" :class="{'group-status-none': record.flag !== 1}">
          {{ record.flag | enumValueByKey($const.CONTRACT_STATUS) }}
        </div>
      </template>
      <template slot="operate" slot-scope="text, record" v-if="!projectClosed">
        <a @click="clickView(record, false)" style="margin-right: 10px" v-if="$auth('PROJECT.PROJECT_MEMBER_DETAIL')">{{ $t('all.autotext568') }}</a>
        <a @click="clickView(record, true)" style="margin-right: 10px" v-if="$auth('PROJECT.PROJECT_MEMBER_EDIT')">{{ $t('all.autotext919') }}</a>
        <a-popconfirm :title="$t('all.autotext145')" @confirm="clickStatus(record)" >
          <a v-if="$auth('PROJECT.PROJECT_MEMBER_STATUS')" style="margin-right: 10px">
            {{ record.flag === 1 ? $t('all.autotext567') : $t('all.autotext307') }}
          </a>
        </a-popconfirm>
        <a-popconfirm :title="$t('all.autotext635')" @confirm="clickRemove(record)">
          <a v-if="$auth('PROJECT.PROJECT_MEMBER_DEL') && record.status === 2">{{ $t('all.autotext379') }}</a>
        </a-popconfirm>
      </template>
    </s-table>
    <!-- 团队成员新增弹框 -->
    <GroupMemberModal
      :projectId="$route.query.id"
      :invitedType="2"
      :modalVisible="modalVisible"
      :modaltitle="$t('all.autotext1392')"
      @closeInvitateModal="closeInvitateModal"
    />
    <!-- 查看团队成员信息弹框 -->
    <ViewMemberModal ref="viewMenberRef"  @refresh="memberRefresh"/>
    <div style="margin: 20px 0"></div>
    <!-- 中心列表 -->
    <s-table
      v-if="$auth('PROJECT.PROJECT_RESEARCH')"
      class="research-table"
      :columns="$auth('PROJECT.PROJECT_RESEARCH_LIST') ? researchColmns:[]"
      bordered
      :data="loadCenterData"
      ref="centerTableRef"
      :row-key="record => record.id"
      :scroll="{ x: 1300 }"
    >
      <template slot="title">
        <div class="research-table--header">
          <span class="title">{{ $t('all.autotext1159') }}</span>
          <!--<div class="btn&#45;&#45;header">-->
          <!--  <a-space>-->
          <!--    <a-button @click="downloadCenterTemplate">-->
          <!--      模版下载-->
          <!--    </a-button>-->
          <!--    <a-button v-if="$auth('PROJECT.PROJECT_RESEARCH_ADD')">-->
          <!--      导入-->
          <!--    </a-button>-->
          <!--    <a-button-->
          <!--      type="primary"-->
          <!--      @click="activeAddCenter()"-->
          <!--      :disabled="$store.state.user.project.status === 3"-->
          <!--      v-if="$auth('PROJECT.PROJECT_RESEARCH_ADD')"-->
          <!--    >-->
          <!--      添加-->
          <!--    </a-button>-->
          <!--  </a-space>-->
          <!--</div>-->
        </div>
      </template>
      <template slot="active" slot-scope="text, record">
        <span>{{ record.active === 1 ? $t('all.autotext193') : (record.active === 2 ? $t('all.autotext892') : '') }}</span>
      </template>
      <template slot="operate" slot-scope="text, record" v-if="!projectClosed">
        <a
          @click="clickEdit(record,1)"
          style="margin-right: 10px"
          v-if="!$auth('PROJECT.PROJECT_RESEARCH_EDIT') && $auth('PROJECT.PROJECT_RESEARCH_DETAIL')"
        >{{ $t('all.autotext568') }}</a>
        <template v-if="notClosed(record)">
          <!--<a @click="clickEdit(record, 2)" style="margin-right: 10px" v-if="$auth('PROJECT.PROJECT_RESEARCH_EDIT')">编辑</a>-->
          <!--<a @click="handleActive(record, 2)" style="margin-right: 10px" v-if="$auth('PROJECT.PROJECT_RESEARCH_OPERATE')">关闭</a>-->
          <!--<a-popconfirm title="是否确认删除？" @confirm="clickDelete(record)" style="margin-right: 10px">-->
          <!--  <a v-if="$auth('PROJECT.PROJECT_RESEARCH_DELETE')">删除</a>-->
          <!--</a-popconfirm>-->
          <a @click="showQrCode(record)">{{ $t('all.autotext858') }}</a>
        </template>
        <template v-else>
          <a @click="handleActive(record, 1)" style="margin-right: 10px" v-if="$auth('PROJECT.PROJECT_RESEARCH_OPERATE')">{{ $t('all.autotext193') }}</a>
        </template>
        <!-- <a-divider type="vertical" /> -->
        <a
          @click="clickEditGroup(record, false)"
          v-if="!$auth('PROJECT.PROJECT_RESEARCH_MEMBER_EDIT') && $auth('PROJECT.PROJECT_RESEARCH_MEMBER_LIST')"
          style="margin-right: 10px"
        >{{ $t('all.autotext336') }}</a>
      <!-- <a
          @click="clickEditGroup(record)"
          v-if="$auth('PROJECT.PROJECT_RESEARCH_MEMBER_EDIT')"
          style="margin-right: 10px"
        >编辑研究团队
        </a> -->
      </template>
    </s-table>
    <!-- 中心编辑弹框 -->
    <UpdateCenterModal
      v-model="updateCenterVisible"
      @refresh="$refs.centerTableRef.refresh(true),$refs.memberTableRef.refresh(true)"
      ref="updateCenterModalRef"
      :openType="openType"
      :centerId="centerId"
    />
    <!-- 研究团队弹框 -->
    <ResearchGroup
      v-model="updateResearchGroupVisible"
      @closeResearchGroup="closeResearchGroup"
      ref="updateResearchGroupRef"
      :centerId="centerId"
      :isHidden="isHiddenEdit"
    />
    <!-- 稽查记录弹窗 -->
    <recordDrawer ref="recordRef"></recordDrawer>
    <!-- 研究中心二维码弹窗 -->
    <qrcodeModal ref="researchQrcode" :data-url="qrcodeDataUrl" :research-center="currentResearchCenter"></qrcodeModal>
  </div>
</template>

<script>
import { memberList, deleteMember, centerList, deleteCenter, reinviteMember, statusTeam, apiCenterActive } from '@/api/overview/member'
import UpdateCenterModal from './members/UpdateCenterModal'
import GroupMemberModal from '@/components/InvitationModal/GroupMemberModal'
import ViewMemberModal from './members/ViewMemberModal'
import ResearchGroup from './members/ResearchGroup'
import recordDrawer from './members/recordDrawer.vue'
import { buildPaginationObj } from '@/components/Table'
import Qrcode from '@/utils/qrcode'
import QrcodeModal from '@views/overview/detail/responsible/components/members/qrcodeModal.vue'
import qs from 'qs'

export default {
  name: 'members',
  inject: {
    detailsInfoFn: {
      type: Function,
      default: () => {}
    }
  },
  components: {
    QrcodeModal,
    UpdateCenterModal,
    GroupMemberModal,
    ViewMemberModal,
    ResearchGroup,
    recordDrawer
  },
  data () {
    const memberColumns = [
      {
        title: this.$t('all.autotext334'),
        dataIndex: 'index',
        width: 100,
        scopedSlots: { customRender: 'index' }
      },
      {
        title: this.$t('all.autotext551'),
        key: 'account',
        width: 150,
        dataIndex: 'account'
      },
      {
        title: this.$t('all.autotext977'),
        key: 'name',
        width: 100,
        dataIndex: 'name'
      },
      {
        title: this.$t('all.autotext898'),
        key: 'roleName',
        width: 100,
        dataIndex: 'roleName'
      },
      {
        title: this.$t('all.autotext1054'),
        key: 'researchName',
        dataIndex: 'researchName'
      },
      {
        title: this.$t('all.autotext1055'),
        key: 'flag',
        width: 130,
        scopedSlots: { customRender: 'flag' }
      },
      {
        title: this.$t('all.autotext187'),
        key: 'operate',
        width: 200,
        scopedSlots: { customRender: 'operate' }
      }
    ]
    const researchColmns = [
      {
        title: this.$t('all.autotext1364'),
        key: 'researchCenterNo',
        dataIndex: 'researchCenterNo'
      },
      {
        title: this.$t('all.autotext400'),
        key: 'orgName',
        dataIndex: 'orgName'
      },
      {
        title: this.$t('all.autotext1086'),
        key: 'pi',
        width: '150px',
        dataIndex: 'pi'
      },
      {
        title: this.$t('all.autotext1117') + 'CRC',
        key: 'userName',
        dataIndex: 'userName'
      },
      {
        title: this.$t('all.autotext1117') + 'CRA',
        key: 'craUserName',
        dataIndex: 'craUserName'
      },
      {
        title: this.$t('all.autotext60'),
        key: 'active',
        dataIndex: 'active',
        scopedSlots: { customRender: 'active' }
      },
      {
        title: this.$t('all.autotext187'),
        key: 'operate',
        fixed: 'right',
        width: 240,
        scopedSlots: { customRender: 'operate' }
      }
    ]
    return {
      proId: '',
      centerId: null,
      openType: 0, // 0新增，1查看，2编辑
      isHiddenEdit: false,
      updateCenterVisible: false,
      memberColumns, // 不区分角色都能看到操作栏
      researchColmns, // 不区分角色都能看到操作栏
      loadCenterData: parameter => {
        if (this.$auth('PROJECT.PROJECT_RESEARCH_LIST')) {
          if (this.proId) {
            return centerList({
              ...parameter,
              proId: this.proId,
              deleted: 0 // 后端让传的写死的字段
            })
          }
        } else {
          return Promise.resolve(buildPaginationObj([]))
        }
      },
      // 研究团队
      modalVisible: false, // 子组件（研究团队成员）是否显示
      loadMemberData: parameter => {
        if (this.$auth('PROJECT.PROJECT_MEMBER_LIST')) {
          if (this.proId) {
            return memberList({
              ...parameter,
              proId: this.proId
            })
          }
        } else {
          return Promise.resolve(buildPaginationObj([]))
        }
      },
      updateResearchGroupVisible: false,
      qrcodeDataUrl: '',
      currentResearchCenter: {}
    }
  },
  computed: {
    detailsInfo () {
      return this.detailsInfoFn()
    },
    projectClosed () {
      return this.$store.state.user?.project?.status === 3
    }
  },
  created () {
    const pd = localStorage.getItem('CURRENT_PROID')
    if (pd) {
      this.proId = parseInt(pd)
    }
  },
  methods: {
    // 查看记录
    getRecord () {
      this.$refs.recordRef.open()
      this.$refs.recordRef.getFeatch()
    },
    /* ********团队成员******** */
    // 添加团队成员
    activeAddMembers () {
      this.modalVisible = true
    },
    // 添加团队成员对话框关闭
    closeInvitateModal (val) {
      if (val) {
        this.$refs.memberTableRef.refresh(true)
        this.$refs.centerTableRef.refresh(true)
      }
      this.modalVisible = false
    },
    // 点击查看团队成员信息
    clickView (record, flag) {
      this.$refs.viewMenberRef.open()
      this.$refs.viewMenberRef.getMemberDetail(record.id, flag)
    },
    memberRefresh () {
      this.$refs.memberTableRef.refresh(true)
      this.$refs.centerTableRef.refresh(true)
    },
    async clickStatus (record) {
      await statusTeam({
        id: record.id,
        flag: record.flag === 1 ? 0 : 1
      })
      this.$refs.memberTableRef.refresh(true)
      this.$refs.centerTableRef.refresh(true)
    },
    // 点击取消
    clickCancel (record) {
      deleteMember({
        id: record.id,
        name: record.name,
        account: record.account,
        roleCode: record.roleCode
      })
        .then(res => {
          this.$emit('cancelMember')
          this.$refs.memberTableRef.refresh(true)
          this.$refs.centerTableRef.refresh(true)
          this.$message.success(this.$t('all.autotext1009'))
        })
        .catch(() => {})
    },
    // 点击重新邀请
    clickReinvite (record) {
      reinviteMember({ proId: this.proId, invitedUserId: record.userId })
        .then(res => {
          this.$refs.memberTableRef.refresh(true)
          this.$refs.centerTableRef.refresh(true)
          this.$message.success(this.$t('all.autotext1205'))
        })
    },
    // 点击移出
    clickRemove (record) {
      deleteMember({
        id: record.id,
        name: record.name,
        account: record.account,
        roleCode: record.roleCode
      })
        .then(res => {
          this.$emit('cancelMember')
          this.$refs.memberTableRef.refresh(true)
          this.$refs.centerTableRef.refresh(true)
          this.$message.success(this.$t('all.autotext1455'))
        })
        .catch(() => {})
    },
    /* ********研究中心******** */
    // 添加中心
    activeAddCenter () {
      this.openType = 0
      this.updateCenterVisible = true
    },
    // downloadCenterTemplate () {
    //   return apiDownloadCenterTemplate()
    // },
    // 未关闭
    notClosed ({ active }) {
      return active !== 2
    },
    // 点击编辑
    clickEdit (record, boo) {
      this.updateCenterVisible = true
      this.centerId = record.id
      this.openType = boo
    },
    /**
     * 研究中心 启动/关闭
     * @param record
     * @param {number} active 1-启动 2-关闭
     */
    handleActive (record, active) {
      const { id } = record
      return apiCenterActive({ researchId: id, active }).then(res => {
        this.$message.success(this.$t('all.autotext470'))
        this.$refs.centerTableRef.refresh()
      })
    },
    // 研究中心点击删除
    clickDelete (record) {
      deleteCenter({
        id: record.id,
        orgName: record.orgName,
        researchCenterNo: record.researchCenterNo
      })
        .then(res => {
          this.$refs.memberTableRef.refresh(true)
          this.$refs.centerTableRef.refresh(true)
        })
        .catch(() => {})
    },
    async showQrCode (record) {
      const { id, proId, orgName, offline } = record
      if (!offline) {
        this.$message.error(this.$t('subject.autotext48'))
        return false
      }
      const params = {
        target: '/wx/invite', // 目标页面
        name: this.detailsInfo.name, // 项目名称
        no: this.detailsInfo.no, // 临床试验方案编号
        proId,
        researchId: id,
        researchName: orgName,
        adminId: this.$store.state.user?.info?.id
      }
      const queryParams = qs.stringify(params)
      const origin = location.origin
      const dataUrl = await Qrcode.generateByText(`${origin}/transfer-page?${queryParams}`)
      // console.log(`${origin}/transfer-page?${queryParams}`)
      this.qrcodeDataUrl = dataUrl
      this.$refs.researchQrcode.setVisible(true)
      this.currentResearchCenter = record
    },
    // 点击研究团队编辑
    clickEditGroup (row, boo = true) {
      this.updateResearchGroupVisible = true
      this.centerId = row.id
      if (!boo) { // 只可查看
        this.isHiddenEdit = true
      }
    },
    // 研究团队对话框关闭
    closeResearchGroup () {
      this.updateResearchGroupVisible = false
      this.$refs.memberTableRef.refresh(true)
      this.$refs.centerTableRef.refresh(true)
    }
  }
}
</script>
<style scoped lang="less">
.title {
  line-height: 32px;
  color: rgba(0, 0, 0, 0.85);
  font-weight: bold;
  font-size: 16px;
}
.group-status {
  padding-left: 14px;
  position: relative;
  &::before {
    content: "";
    display: block;
    width: 6px;
    height: 6px;
    background: rgb(3, 205, 3);
    border-radius: 50%;
    position: absolute;
    left: 0;
    top: 9px;
  }
}
.group-status-none {
  &::before {
    background: rgb(239, 145, 3);
  }
}
.research-table {
  .research-table--header {
    display: flex;
    justify-content: space-between;
  }
}
</style>
